package com.mars.module.oss.common.config;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.SysOss;
import com.mars.module.admin.service.ISysOssService;
import com.mars.module.oss.common.enums.FileUploadTypeEnums;
import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class MinIoClientConfig {


    @Resource
    private ISysOssService sysOssService;


    /**
     * 注入minio 客户端
     *
     * @return MinioClient
     */
    @Bean
    @ConditionalOnProperty(prefix = "easy.admin", name = "fileUploadType", havingValue = "minio")
    public MinioClient minioClient() {
        List<SysOss> list = sysOssService.list(FileUploadTypeEnums.MINIO.getType());
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("oss未配置");
        }
        SysOss sysOss = list.get(0);
        return MinioClient.builder()
                .endpoint(sysOss.getEndpoint())
                .credentials(sysOss.getAccessKey(), sysOss.getSecretKey())
                .build();
    }
}
